package com.ssy.lingxi.platform.manage.serviceimpl;

import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.model.dto.rule.RuleConfigurationDTO;
import com.ssy.lingxi.platform.manage.api.model.dto.rule.RuleConfigurationListDTO;
import com.ssy.lingxi.platform.manage.api.model.vo.rule.RuleConfigurationVO;
import com.ssy.lingxi.platform.manage.entity.base.RuleConfiguration;
import com.ssy.lingxi.platform.manage.repository.RuleConfigurationRepository;
import com.ssy.lingxi.platform.manage.service.RuleConfigurationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu 平台规则配置 - 业务实现层
 * @author wrc
 * @version 2.0.0
 * @date 2020/7/20
 */
@Service
public class RuleConfigurationServiceImpl implements RuleConfigurationService {

    @Resource
    private RuleConfigurationRepository ruleConfigurationRepository;

    /**
     * 查询平台规则配置
     */
    @Override
    public Wrapper<List<RuleConfigurationVO>> ruleConfigurationList(RuleConfigurationListDTO request) {
        List<RuleConfiguration> all = ruleConfigurationRepository.findAllByIsPitchOnEqualsAndPlatformTypeEquals(CommonConstant.State.STATE_START,request.getPlatformType());
        List<RuleConfigurationVO> collect = all.stream().map(temp -> {
            RuleConfigurationVO ruleConfigurationResponse = new RuleConfigurationVO();
            ruleConfigurationResponse.setValue(temp.getId());
            ruleConfigurationResponse.setPlatformType(temp.getPlatformType());
            ruleConfigurationResponse.setCheck(temp.getIsPitchOn());
            ruleConfigurationResponse.setLabel(temp.getPlatformWayName());
            return ruleConfigurationResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }

    /**
     * 修改平台规则配置
     */
    @Override
    @Transactional
    public Wrapper<Void> ruleConfigurationUpdate(RuleConfigurationDTO request) {
        ruleConfigurationRepository.deleteAll();
        List<RuleConfiguration> list=new ArrayList<>();
        request.getRuleConfigurations().forEach(ruleConfiguration -> {
            RuleConfiguration ruleConfigurationNew=new RuleConfiguration();
            ruleConfigurationNew.setIsPitchOn(ruleConfiguration.getCheck());
            ruleConfigurationNew.setPlatformType(ruleConfiguration.getPlatformType());
            ruleConfigurationNew.setPlatformWayName(ruleConfiguration.getLabel());
            ruleConfigurationNew.setId(ruleConfiguration.getValue());
            list.add(ruleConfigurationNew);
        });
        ruleConfigurationRepository.saveAll(list);
        return Wrapper.success();
    }
}
